
import { getPlanSummary,getAllDietRecordsByUserId,deleteRecordAndFoodEntry,deletePlanFoodById } from '../../http/api';
import eventBus from '../../utils/eventBus';

const app = getApp();
Page({
  data: {
    mealId: '', // 当前餐次类型
    userId: '', // 用户ID
    meals: [], // 所有餐次的数据
    currentMeal: {
      mealType: 1,
      mealName: '早餐',
      selectedFoods: [],
      totalCalories: 0,
      totalProtein: 0,
      totalFat: 0,
      totalCarbohydrate: 0
    }, // 当前选中的餐次
    isEditMode: false // 是否为编辑模式
  },

  onLoad: function (options) {
    const { mealId, action } = options;
    this.setData({ 
      mealId,
      userId: wx.getStorageSync('userInfo').userId,
      isEditMode: action === 'edit',
      meals: app.globalData.meals
    });

    if (this.data.isEditMode) {
      this.loadPlanSummary();
    } else {
      this.loadMeals();
    }    
    // 监听食物添加事件
    eventBus.on('foodAdded', (data) => {     
      this.onLoad(data)
      // this.addFood(data);              
    });        
  },  
  onUnload(){
    eventBus.off('foodAdded');
  },

  navigateBack: function () {
    wx.navigateBack({
      delta: 1 // 返回的页面数，如果 delta 大于现有页面数，则返回到首页。
    });
  },
  
  // 更新食物列表和营养汇总
  updateFoodList(records) {
    let totalCalories = 0,
      totalProtein = 0,
      totalFat = 0,
      totalCarbohydrate = 0;

    const selectedFoods = records.map((record) => {
      totalCalories += parseFloat(record.calories);
      totalProtein += parseFloat(record.protein);
      totalFat += parseFloat(record.fat);
      totalCarbohydrate += parseFloat(record.carbohydrate);

      return {
        foodId: record.foodId,
        foodEntryId: record.foodEntryId,
        recordId:record.recordId,
        name: record.foodName || '未知食物',
        grams: record.grams,
        calories: parseFloat(record.calories).toFixed(1),
        protein: parseFloat(record.protein).toFixed(1),
        fat: parseFloat(record.fat).toFixed(1),
        carbohydrate: parseFloat(record.carbohydrate).toFixed(1)
      };
    });

    this.setData({
      selectedFoods,
      totalCalories: parseFloat(totalCalories.toFixed(1)),
      totalProtein: parseFloat(totalProtein.toFixed(1)),
      totalFat: parseFloat(totalFat.toFixed(1)),
      totalCarbohydrate: parseFloat(totalCarbohydrate.toFixed(1))
    });
  },
  /**
   * 跳转到食物列表页面
   */
  chooseFood() {
    if(this.data.isEditMode)
    {
      wx.navigateTo({
        url: `/pages/heat/heat?mealType=${this.data.currentMeal.mealType}&action=edit`
      });
    }else{
      wx.navigateTo({
        url: `/pages/heat/heat?mealType=${this.data.currentMeal.mealType}`
      });
    }    
  },

  
  /**
   * 添加食物到当前餐次
   */
  // addFood(params) {
  //   const { mealType, food, grams, foodEntryId, recordId } = params;
  //   let updatedMeals = this.data.meals.map(meal => {
  //     if (meal.mealType === mealType) {
  //       // 计算营养成分
  //       const calories = food.calories * grams / 100;
  //       const protein = food.protein * grams / 100;
  //       const fat = food.fat * grams / 100;
  //       const carbohydrate = food.carbohydrate * grams / 100;

  //       // 添加新的食物项到selectedFoods
  //       meal.selectedFoods.push({
  //         foodId: food.id,
  //         foodEntryId,
  //         recordId,
  //         name: food.name,
  //         grams: grams,
  //         calories: (calories).toFixed(1),
  //         protein: (protein).toFixed(1),
  //         fat: (fat).toFixed(1),
  //         carbohydrate: (carbohydrate).toFixed(1),
  //         isSwiped: false
  //       });

  //       // 更新总营养值
  //       meal.totalCalories = (parseFloat(meal.totalCalories) + calories).toFixed(1);
  //       meal.totalProtein = (parseFloat(meal.totalProtein) + protein).toFixed(1);
  //       meal.totalFat = (parseFloat(meal.totalFat) + fat).toFixed(1);
  //       meal.totalCarbohydrate = (parseFloat(meal.totalCarbohydrate) + carbohydrate).toFixed(1);
  //     }
  //     return meal;
  //   });    
  //   // 更新页面数据
  //   this.setData({ meals: updatedMeals });
  
  // },
  // 选中餐次后显示
  onMealTabTap(e) {
    const mealType = e.currentTarget.dataset.mealType;
    const currentMeal = this.data.meals.find(meal => meal.mealType == mealType);
    this.setData({ currentMeal });
  },
  //加载餐次
  loadMeals() {
    const { mealId, userId } = this.data;   
    wx.showLoading({ title: '加载中...' });
  
    getAllDietRecordsByUserId(userId)
    .then((res) => {
      wx.hideLoading();        
      
      if (res.data.success) {        
        const records = res.data.data;
        const formattedFoods = this.formatFoodItems(records);
          
        // 初始化 meals 数据
        const meals = [
          { mealType: 1, mealName: '早餐', selectedFoods: [], totalCalories: 0, totalProtein: 0, totalFat: 0, totalCarbohydrate: 0 },
          { mealType: 2, mealName: '午餐', selectedFoods: [], totalCalories: 0, totalProtein: 0, totalFat: 0, totalCarbohydrate: 0 },
          { mealType: 3, mealName: '晚餐', selectedFoods: [], totalCalories: 0, totalProtein: 0, totalFat: 0, totalCarbohydrate: 0 },
          { mealType: 4, mealName: '加餐', selectedFoods: [], totalCalories: 0, totalProtein: 0, totalFat: 0, totalCarbohydrate: 0 }
        ];          
        // 根据 mealType 分配食物到对应的餐次
        formattedFoods.forEach(food => {
          const meal = meals.find(m => m.mealType === food.mealType);
          if (meal) {            
            meal.selectedFoods.push(food);
            meal.totalCalories += parseFloat(food.calories);
            meal.totalProtein += parseFloat(food.protein);
            meal.totalFat += parseFloat(food.fat);
            meal.totalCarbohydrate += parseFloat(food.carbohydrate);
          }
        });  
        // 将当前的meals赋予全局变量
        app.globalData.meals = meals;          
        this.setData({
          meals,
          currentMeal: meals.find(meal => meal.mealType == mealId) || meals[0]          
        });       
      } else {
        wx.showToast({ title: '暂无记录', icon: 'none' });
      }
    })
    .catch(error => {
      wx.hideLoading();
      wx.showToast({ title: '加载失败', icon: 'none' });
    });      
    },
    // 加载计划餐次
    loadPlanSummary() {
      getPlanSummary(this.data.userId)
      .then(res => {
        if (res.data.success) {
          const { meals } = res.data;       
          app.globalData.meals = meals;
          this.setData({
            meals,
            currentMeal: meals.find(meal => meal.mealType == 1) || {}
          });          
        } else {
          wx.showToast({ title: res.message, icon: 'none' });
        }
      })
      .catch(err => wx.showToast({ title: '加载计划摘要失败', icon: 'none' }));
  },
  
  formatFoodItems(records) {
    const formatted = records.map(item => ({
      foodEntryId:item.foodEntryId,
      foodId: item.foodId,
      name: item.foodName || '未知食物',
      grams: item.grams,
      calories: item.calories.toFixed(1),
      protein: item.protein.toFixed(1),
      fat: item.fat.toFixed(1),
      carbohydrate: item.carbohydrate.toFixed(1),
      mealType: item.mealType,
      isSwiped: false // 添加默认值
    }));
    return formatted;
  },
    /**
   * 处理左滑事件
   */
  onSwipeChange(e) {
    const { index } = e.currentTarget.dataset;
    const currentMeal = this.data.currentMeal;

    // 更新当前食物项的左滑状态
    currentMeal.selectedFoods[index].isSwiped = e.detail.x < -40; // 判断是否滑动超过一定距离

    this.setData({
      currentMeal
    });
  },
   /**
   * 删除食物项
   */
  deleteFood(e) {
    const { index } = e.currentTarget.dataset;
    const currentMeal = this.data.currentMeal;

    // 弹出确认提示框
    wx.showModal({
      title: '确认删除',
      content: '确定要删除该食物吗？',
      success: (res) => {
        if (res.confirm) {      
           // 删除对应的食物项
           const deletedFood = currentMeal.selectedFoods.splice(index, 1)[0];
          if (this.data.isEditMode) {
            deletePlanFoodById(deletedFood.planId)
              .then(res => {
                if (res.success) {
                  wx.showToast({ title: "删除成功", icon: 'none' });  
              }
            })
          } else {
            deleteRecordAndFoodEntry(deletedFood.foodEntryId)
            .then(res => {
              if (res) {
                wx.showToast({ title: "删除成功", icon: 'none' });  
              }              
            })
          }
                             
          // 更新营养汇总数据
          currentMeal.totalCalories = (
            parseFloat(currentMeal.totalCalories) - parseFloat(deletedFood.calories)
          ).toFixed(1);
          currentMeal.totalProtein = (
            parseFloat(currentMeal.totalProtein) - parseFloat(deletedFood.protein)
          ).toFixed(1);
          currentMeal.totalFat = (
            parseFloat(currentMeal.totalFat) - parseFloat(deletedFood.fat)
          ).toFixed(1);
          currentMeal.totalCarbohydrate = (
            parseFloat(currentMeal.totalCarbohydrate) - parseFloat(deletedFood.carbohydrate)
          ).toFixed(1);

          // 更新全局状态中的餐次数据
          const meals = app.globalData.meals.map(meal =>
            meal.mealType === currentMeal.mealType ? currentMeal : meal
          );
          app.globalData.meals = meals;

          // 更新页面数据
          this.setData({
            currentMeal,
            meals
          });
        }
      }
    });
  },
});